<template>
  <div v-loading="loading" class="AddOrUpdate_main add_container column_three">
    <div class="main_main">
      <el-form ref="form" :model="formData" :rules="rules" :inline="true">
        <el-form-item label="BOM编码" prop="code">
          <CodeRuleInput :band-value.sync="formData.code" table-name="engineering_bom" column-name="code" :is-edit="tagId&&tag == 'edit'" />
          <!--          <el-input v-else v-model="formData.code" placeholder="暂无" disabled />-->
        </el-form-item>
        <el-form-item v-if="tag!='reviseEdition'" label="物料编码" class="clickChoose" prop="materialCode">
          <el-input v-model="formData.materialCode" placeholder="请选择" readonly />
          <a
            class="clickChoose_button"
            @click.prevent="chooseMaterial"
          >
            <svg-icon icon-class="选择弹框" />
          </a>
        </el-form-item>
        <el-form-item v-else label="物料编码" prop="materialCode">
          <el-input v-model="formData.materialCode" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="物料名称">
          <el-input v-model="formData.materialName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="formData.materialModel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="物料分类">
          <el-input v-model="formData.materialTypeName" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="物料单位">
          <el-input v-model="formData.materialUnitLabel" placeholder="暂无" disabled />
        </el-form-item>
        <el-form-item label="版本号" prop="versionCode">
          <el-input v-model="formData.versionCode" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="附件" class="double">
          <FileManageFull
            :file-names="formData.fileName"
            :file-real-names="formData.fileRealName"
            :file-urls="formData.fileUrl"
            :row-index="1"
            @fileName="setFileName"
          />
        </el-form-item>
        <el-form-item label="备注" class="double">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <div class="bom_bottom">
        <div class="bom_bottom_detail">

          <div class="formItem_header formItem_header_padding">
            子级物料
            <div class="formItem_header_operate">
              <a class="formItem_header_operate_item" @click="chooseMaterialChildren">
                <svg-icon icon-class="新增" />
                <div class="item_name">添加</div>
              </a>
              <a class="formItem_header_operate_item delete" @click="deleteRow">
                <svg-icon icon-class="删除" />
                <div class="item_name">删除</div>
              </a>
            </div>
          </div>

          <div ref="table_container" class="table_container table_container1">
            <el-table
              :data="tableData"
              stripe
              border
              :header-cell-class-name="headerCellClassName"
              @selection-change="selectionChange"
            >
              <el-table-column
                type="selection"
                width="70"
                align="center"
              />
              <el-table-column label="物料编码" min-width="120" prop="materialCode" :show-overflow-tooltip="true" />
              <el-table-column label="物料名称" min-width="100" prop="materialName" :show-overflow-tooltip="true" />
              <el-table-column label="规格型号" min-width="100" prop="materialModel" :show-overflow-tooltip="true" />
              <el-table-column label="物料分类" min-width="100" prop="materialTypeName" :show-overflow-tooltip="true" />
              <el-table-column label="物料单位" min-width="100" prop="materialUnitLabel" :show-overflow-tooltip="true" />
              <el-table-column label="需求数量" fixed="right" :min-width="SETTINGS.settings_decimalDigits_length" prop="needNumber">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.needNumber"
                    clearable
                    @change="handleNumberChange"
                  />
                </template>
              </el-table-column>
              <el-table-column label="替代料" min-width="150">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.replaceMaterialCodeNames"
                    readonly
                    placeholder="请选择"
                    @click.native="chooseReplaceMaterial(scope.row,scope.$index)"
                  />
                </template>
              </el-table-column>

              <el-table-column label="备注" min-width="100" prop="remark">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入"
                    clearable
                  />
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

    </div>
    <div class="main_bottom">
      <el-button type="cancel" @click.stop="cancel">取消</el-button>
      <el-button v-if="tag!='reviseEdition'" @click.stop="onSubmit('0')">保存</el-button>
      <el-button @click.stop="onSubmit('1')">提交</el-button>
    </div>
  </div>
</template>

<script>
import { addOrUpdate, getInfo, bomExchange } from '@/api/engineeringManage/BOMManage'
import chooseMaterial from './chooseMaterial'
import chooseReplaceMaterial from './chooseReplaceMaterial'
import chooseMaterialChildren from './chooseMaterialChildren'
const _ = require('lodash')
export default {

  name: 'AddOrUpdate',
  props: {
    layerid: {},
    id: {},
    defaultValue: {},
    tag: {},
    tagId: {}
  },
  data() {
    return {
      loading: true,
      isShow: false,
      formData: {
        id: undefined,
        code: undefined,
        versionCode: '',
        materialId: undefined,
        materialCode: undefined,
        materialName: undefined,
        materialModel: undefined,
        materialTypeName: undefined,
        materialUnitLabel: undefined,
        fileName: '',
        fileRealName: '',
        fileUrl: '',
        remark: undefined,
        status: '1'
      },
      tableData: [],
      rules: {
        materialCode: [
          { required: true, message: '物料不能为空', trigger: 'change' }
        ],
        versionCode: [
          { required: true, message: '版本号不能为空', trigger: 'change' }
        ],
        code: [
          { required: true, message: 'BOM编码不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.tag == 'add') { // 新增
      this.loading = false
    }
    if (this.tag == 'edit') { // 编辑
      this.getInfo()
    }
    if (this.tag == 'copy') { // 复制
    }
    if (this.tag == 'reviseEdition') { // 升版
      getInfo(this.tagId).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          if (key != 'code') { this.formData[key] = res.data[key] }
        })
        this.tableData = res.data.data

        this.formData.id = ''
        this.formData.versionCode = ''
        this.isShow = false
        this.loading = false
      })
    }
    if (this.tag == 'change') { // 变更
      getInfo(this.tagId).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.formData.versionCode = ''
        delete this.formData['id']
        this.loading = false
      })
    }
  },
  methods: {
    setFileName(...data) {
      this.formData.fileName = data[0]
      this.formData.fileRealName = data[1]
      this.formData.fileUrl = data[2]
    },
    headerCellClassName(data) {
      if (['needNumber'].indexOf(data.column.property) != -1) {
        return 'column_bt'
      }
    },
    getInfo() {
      getInfo(this.tagId).then(res => {
        Object.keys(this.formData).forEach(key => { // 给右边数据赋值
          this.formData[key] = res.data[key]
        })
        this.tableData = res.data.data
        this.isShow = true
        this.loading = false
      })
    },
    onSubmit(num) {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const json = this.$deepClone(this.formData)
          json.status = num
          json.data = this.$deepClone(this.tableData)
          let tag = true
          if (tag && this.tableData.length == 0) {
            this.$message({
              message: '子级物料不能为空',
              type: 'warning'
            })
            tag = false
          }
          if (tag && this.tableData.length > 0 && this.tableData.filter(item => !item.needNumber).length > 0) {
            this.$message({
              message: '需求数量不能为空',
              type: 'warning'
            })
            tag = false
          }
          if (tag && this.tableData.length > 0 && this.tableData.filter(item => !this.SETTINGS.reg_no_zero.test(item.needNumber)).length > 0) {
            this.$message({
              message: '需求数量错误',
              type: 'warning'
            })
            tag = false
          }
          if (tag) {
            if (this.tag == 'change') {
              bomExchange(json).then(res => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.$layer.close(this.layerid) // 关闭弹框
                this.$parent.refresh() // 调用父组件的刷新方法
              })
            } else {
              addOrUpdate(json).then(res => {
                this.$message({
                  message: res.msg,
                  type: 'success'
                })
                this.$layer.close(this.layerid) // 关闭弹框
                this.$parent.refresh() // 调用父组件的刷新方法
              })
            }
          }
        }
      })
    },
    cancel() {
      this.$layer.close(this.layerid)// 关闭弹框
    },

    chooseMaterial() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.formData
          }
        },
        area: ['1320px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseMaterialCallBack(row) {
      this.formData.materialId = row.id
      this.formData.materialCode = row.materialCode
      this.formData.materialName = row.materialName
      this.formData.materialModel = row.materialModel
      this.formData.materialTypeName = row.materialTypeName
      this.formData.materialUnitLabel = row.materialUnitName
      // 如果已经选了子物料，且子物料里面有父级物料，那从子物料里删除
      this.tableData.forEach((item, index) => {
        if (item.materialId == this.formData.materialId) {
          this.tableData.splice(index, 1)
        }
      })
    },
    chooseMaterialChildren() {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseMaterialChildren, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: this.tableData,
            excludeSelect: [this.formData.materialId]
          } // 当前主物料和当前点击的父级物料不能勾选
        },
        area: ['1320px', '700px'],
        title: '选择物料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseMaterialChildrenCallBack(rowList) {
      if (!rowList) {
        return
      }
      const cacheTableData = []
      rowList.forEach(item => {
        item.materialUnitLabel = item.materialUnitName
        if (!this.tableData.some(item2 => item2.materialId == item.materialId)) {
          delete item['id']
          item.remark = ''
          cacheTableData.push(item)
        } else {
          cacheTableData.push((this.tableData.filter(item2 => item2.materialId == item.materialId))[0])
        }
      })

      this.tableData = cacheTableData
      this.handleNumberChange()
    },

    selectionChange(row) {
      this.selectionsAll = row
    },
    deleteRow() {
      this.selectionsAll.forEach(item => {
        this.tableData.splice(this.tableData.indexOf(item), 1)
      })
      this.handleNumberChange()
    },
    // 需求数量发生变化时触发
    handleNumberChange() {
    },
    chooseReplaceMaterial(row, index) {
      this.$layer.iframe({
        // 弹框
        content: {
          content: chooseReplaceMaterial, // 传递的组件对象
          parent: this, // 当前的vue对象
          data: {
            selectedRow: row.replaceMaterialIds ? row.replaceMaterialIds.split(',').map(item => { return { materialId: Number(item) } }) : '',
            index: index,
            excludeSelect: [row.materialId]
          }
        },
        area: ['1320px', '700px'],
        title: '选择替代料', // 标题
        shadeClose: false // 点击遮罩是否关闭
      })
    },
    chooseReplaceMaterialCallBack(rows, index) {
      const cacheTable = this.$deepClone(this.tableData)
      cacheTable[index].replaceMaterialIds = (rows.map(item => item.materialId)).join(',')
      cacheTable[index].replaceMaterialCodeNames = (rows.map(item => item.materialCode + '/' + item.materialName)).join(',')
      this.tableData = this.$deepClone(cacheTable)
      this.selectionsAll = []
    }
  }
}
</script>

<style lang="less" scoped>
.MaterialName {
  display: flex;
  padding: 15px;
  padding-top: 18px !important;
  flex: 1;
  color:rgb(244,156,31);
  text-align: center;
  font-size: 16px;
  align-items: center;
  margin-bottom: 3px;
  .MaterialNameName{
    max-width: 450px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .MaterialNameIcon {
    padding: 2px 5px 0 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}
.table_container1 {
  padding-bottom: 20px !important;
}
.bom_bottom{
  display: flex;
  border-top: 1px solid rgba(105,105,105,0.2);
  .bom_bottom_tree{
    width: 30%;
    border-right: 1px solid rgba(105,105,105,0.2);
    .tree_header{
      height: 50px;
      margin: 0 20px;
      display: flex;align-items: center;
      font-size: 14px;
      color: #333333;
      border-bottom: 1px solid #387BFC;
    }
    .tree_container{
      margin: 0 20px;
      overflow-x: auto;
      width: calc(100% - 40px);
      /deep/ .el-tree-node__content{
        height: 40px;
        .tree-node{
          flex: 1;
          display: flex;justify-content: space-between;align-items: center;
        }
        .node_operate{
          display: flex;align-items: center;
          .node_operate_item{
            display: flex;justify-content: center;align-items: center;
            margin-right: 20px;
          }
        }
        .el-tree-node__children{
          background-color: transparent;
        }

      }
      /deep/ .el-tree-node__children{
        min-width: fit-content;
      }

      /deep/ .el-tree-node__content:hover{
        background-color: rgba(56,123,252,0.5);
        color: white;
      }
    }
  }
  .bom_bottom_detail{
    width: 100%;
    .formItem_header_padding{
      margin-top: 3px;
    }
  }
}
</style>
